package com.lagou.niancheng.lagouserviceuser.controller;

import com.lagou.niancheng.lagou.service.common.Result;
import com.lagou.niancheng.lagou.service.common.ResultBuilder;
import com.lagou.niancheng.lagouserviceuser.common.entity.UserLoginDTO;
import com.lagou.niancheng.lagouserviceuser.common.entity.UserRegisterDTO;
import com.lagou.niancheng.lagouserviceuser.service.TokenService;
import com.lagou.niancheng.lagouserviceuser.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;


@RestController
@RequestMapping("/user")
@Api("用户相关接口")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;

    @PostMapping("/register")
    @ApiOperation("注册")
    public Result<Boolean> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        userService.register(userRegisterDTO);
        return ResultBuilder.toSuccess(null);
    }

    @GetMapping("/isRegistered/{email}")
    @ApiOperation("判断邮箱是否已经注册")
    public Result<Boolean> checkRegistered(@PathVariable("email") String email, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        System.out.println(Arrays.asList(cookies));
        return ResultBuilder.toSuccess(userService.checkRegistered(email));
    }

    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<String> login(@RequestBody UserLoginDTO userLoginDTO, HttpServletResponse response) {
        return ResultBuilder.toSuccess(userService.login(userLoginDTO, response));
    }

    @GetMapping("/info/{token}")
    @ApiOperation("获取邮件")
    public Result<String> getEmail(@PathVariable("token") String token) {
        return ResultBuilder.toSuccess(userService.getEmail(token));
    }

    @GetMapping("/check/{token}")
    @ApiOperation("校验token")
    public Result<Boolean> checkToken(@PathVariable("token") String token) {

        return ResultBuilder.toSuccess(tokenService.checkToken(token));
    }

    @Value("${lagou.test.config}")
    private String config;

    @GetMapping("/test")
    @ApiOperation("测试拦截接口")
    public Result<String> test() {
        return ResultBuilder.toSuccess(config);
    }
}
